<?php 
/**
 * 车辆model类
 * @Author    紫梦
 * @DateTime  2017-11-08
 * @copyright 响响租车
 * @version   1.0
 */
namespace app\common\model;
use think\Model;
use think\Db;
use traits\model\SoftDelete;

class Cars extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $autoWriteTimestamp = true;
    protected $type = [
        'registr_time'  =>  'timestamp:Y-m-d',        
    ];
    protected $insert = ['agency_id'];
    
    protected function setFranchiseeIdAttr()
    {
        return session('admin.agency_id');
    }

    // 定义全局的查询范围
    protected function base($query)
    {
        $agency = session('admin.agency_id');
        if($agency==1){
            $query->where('delete_time',null);

        }else{
            $query->where(['agency_id'=>$agency,'delete_time'=>null]);

        }
                    
    }

    
    //获取器获取所有人名称
    public function getHolderNameAttr($value,$data)
    {
        if($data['holder_type'] ==0){
            return Db::name('company')->where(['id'=>$data['holder_id']])->value('name');
        }else{
            return Db::name('personal')->where(['id'=>$data['holder_id']])->value('name');
        }
    }
    //获取器获取经销商名称
    // public function getAgencyNameAttr($value,$data)
    // {
    //  return Db::name('Agency')->where(['id'=>$data['agency_id']])->value('name');
    // }
    // //获取器获取品牌名称
    // public function getBrandNameAttr($value,$data)
    // {
    //  return Db::name('brand')->where(['id'=>$data['brand_id']])->value('name');
    // }

    public function carFile()
    {
        return $this->hasMany('CarFile','car_id','car_id');
    }

    public function bolutu()
    {
        return $this->hasOne('Yyyymmdd','car_unique_id','car_unique_id')->cache(60)->field('car_unique_id,machine_version,network_status,voltage,time');
    }

    public function brand()
    {
        return $this->hasOne('Brand','id','brand_id')->field('id,name');
    }

    public function agency()
    {
        return $this->hasOne('Agency','id','agency_id')->field('id,name');
    }

    public function carInfo()
    {
        return $this->hasOne('CarInfo','car_unique_id','car_unique_id')->cache(60)->field('car_unique_id,machine_version,network_status,voltage,machine_report_time,time');
    }

    public function carsInfo()
    {
        return $this->hasOne('CarsInfo','car_unique_id','car_unique_id')->field('car_unique_id,machine_version,network_status,voltage,machine_report_time,time');
    }

}